/**
 * Created by smp on 2017/4/24.
 */
var modelPath=ROOT_PATH+'/majorHazard/informationRegistration/';
//初始化下拉树
$('#belongsUnit').combotree({
    url: ROOT_PATH+'/permission/department/getDepartmentTree.shtml?parentId=0'
});
function monthLoop(a,b) {
    if(a.substr(0,1)=="0"){
        a=a.substr(1,1);
    }
    if(b.substr(0,1)=="0"){
        b=b.substr(1,1);
    }
    return parseInt(b)-parseInt(a)+1;
}
function yearMonth(yearMonth,num){
    var year=yearMonth.substr(0,4);
    var month=yearMonth.substr(5,2);
    var months=parseInt(month)+num;
    if(month.substr(0,1)=="0"){
        months=parseInt(month.substr(1,1))+num;
    }
    year=parseInt(year)+parseInt((months-1)/12);
    month=months%12;
    if(month==0){
        month=12;
    }
    if(month<10){
        month="0"+month;
    }
        return year+"-"+month;
}
function getDate(date) {
    var year=date.getFullYear();
    var month=date.getMonth()+1;
    var day=date.getDate();
    if(month<10){
        month="0"+month;
    }
    if(day<10){
        day="0"+day;
    }
    return year+"-"+month+"-"+day;
}
var getContractRecord=function(selected){
    var contactName=selected.contractName;
    var beginDate=selected.beginDate;
    var endDate=selected.endDate;
    var beginYear=beginDate.substring(0,4);
    var beginMonth=beginDate.substring(5,7);
    var endYear=endDate.substring(0,4);
    var endMonth=endDate.substring(5,7);
    var num=0;
    if(beginYear==endYear){
       num=monthLoop(beginMonth,endMonth);
    }else{
        num=(parseInt(endYear)-parseInt(beginYear))*12+monthLoop(beginMonth,endMonth);
    }
    var date=new Date();
    var rows = $('#precautionList').datagrid('getData').rows;
    for(var i=0;i<num;i++){
        var flag=true;
        for(var j=0;j<rows.length;j++){
            if(rows[j].contactMonth==yearMonth(beginDate,i)){
                flag=false;
            }
        }
        if(flag){
            $('#precautionList').datagrid('insertRow',{
                index: 0,  // 索引从0开始
                row: {
                    contactContractorName: contactName,
                    contactMonth: yearMonth(beginDate,i),
                    addTime: getDate(date)
                }
            });
        }
    }
};

var getSelectedContractor = function (data) {

    var code=data[0].code;
    var name=data[0].name;
    for(var i=1;i<data.length;i++){
        code=code+","+data[i].code;
        name=name+","+data[i].name;
    }

    $("#devicePartCode").textbox("setValue",code);
    $("#devicePartName").textbox("setValue",name);

};
$('#devicePartCode').textbox({
    required: true,
    icons: [{
        iconCls: 'icon-search',
        handler: function () {
            WindowManager.openLayer({
                type: 2,
                title: '装置/部位',
                area: ['90%', '70%'],
                content: ROOT_PATH + '/majorHazard/deviceLocation/simpleList.shtml',
                callBack:getSelectedContractor
            });
        }
    }],
    editable: false
});

var getSelectedUser = function (data) {

    $("#contactContractor").val(data[0].id);
    $("#contactContractorName").textbox("setValue",data[0].realName);

};

$('#contactContractorName').textbox({
    required: true,
    icons: [{
        iconCls: 'icon-search',
        handler: function () {
            WindowManager.openLayer({
                type: 2,
                title: '添加报告人',
                area: ['90%', '70%'],
                content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=1',
                callBack:getSelectedUser
            });
        }
    }],
    editable: false
});

$("#precautionList").datagrid({
    method: 'post',
    url: modelPath + 'dataList.shtml',
    queryParams: {
        messageId:$(":input[name=id]").val()
    },
    iconCls: 'icon-save', //图标
    rownumbers:true,
    singleSelect:true,
    fit: true, //datagrid自适应宽度
    fitColumns: true, //列自适应宽度
    striped: true, //行背景交换
    nowap: true, //列内容多时自动折至第二行
    toolbar:'#tb',
    pagination:false,
    columns: [[//显示的列
        {field:'messageId',width:100,checkbox:true},
        {field:'contactContractorName',title:'联系承包人',width:200},
        {field:'contactMonth',title:'承包月份',width:200},
        {field:'addTime',title:'登记日期',width:300}
    ]]
});

//表单提交
$('#btn_save').on('click',function () {
    var index=layer.confirm('是否确定保存？', {
        btn: ['确定','取消'] //按钮
    }, function(){
        var data = $('#precautionList').datagrid('getData');
        var json=JSON.stringify(data.rows);
        $('#form1').form('submit', {
            url: modelPath+'edit.shtml',

            onSubmit: function (param) {
                param.contractRecord=json;
                var isValid = $(this).form('validate');
                if (!isValid) {
                    layer.close(index);
                    layer.msg("请正确填写表单")
                }
                return $(this).form('validate');
            },
            success: function (result) {
                result = $.parseJSON(result);
                if (result.success){
                    //$.messager.progress('close');	// 如果提交成功则隐藏进度条
                    layer.msg(result.message,{time:1000,icon:1},function () {
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                        $.getIframeWindow().$('#dg1').datagrid('load');
                    });
                }else {
                    //$.messager.progress('close');	// 如果提交成功则隐藏进度条
                    parent.layer.msg(result.message,{time:1000,icon:2});
                }
            }
        });
    });

});
$("#btn_precaution_add").on('click',function () {
    var contractName=$("#contactContractorName").textbox("getValue");
    var endDate=$("#endTime").datebox("getValue");
    var beginDate=$("#beginTime").datebox("getValue");
    layer.open({
        type: 2,
        title: '新增承包记录',
        area: ['50%', '40%'],
        content:modelPath+"contractRecord.shtml?endDate="+endDate+"&contractName="+contractName+"&beginDate="+beginDate
    });
});

/**
 * 时间限制
 * @param month
 * @returns {*}
 */
function toMonth(month) {
    month=month+1;
    if(month<10)
        return "0"+month;
    else
        return month;
}
function toDate(date) {
    if(date<10)
        return "0"+date;
    else
        return date;
}
$(function(){
    $("#beginTime").datebox().datebox("calendar").calendar({
        validator:function(date){
            var dateTime=date.getFullYear()+"-"+toMonth(date.getMonth())+"-"+toDate(date.getDate());
            var endTime=$("#endTime").textbox("getValue");
            if(endTime==null||endTime==""){
                return true;
            }else {
                return dateTime<=endTime;
            }
        }
    });
    $("#endTime").datebox().datebox("calendar").calendar({
        validator:function(date){
            var dateTime=date.getFullYear()+"-"+toMonth(date.getMonth())+"-"+toDate(date.getDate());
            var beginTime=$("#beginTime").textbox("getValue");
            if(beginTime==null||beginTime==""){
                return true;
            }else {
                return dateTime>=beginTime;
            }
        }
    });
});